const host = window.location.hostname;
// let user = sessionStorage.getItem('user');
// WebSocket连接
let ws = new WebSocket(`ws://${host}:8080/AVR/websocket/${userId}/${userName}`);
//消息容器
const messagesContainer = document.getElementById('messages1');
//要发送的消息
const messageInput = document.getElementById('message-input');

// 连接事件
ws.onopen = () => {
    console.log('已连接到聊天服务器');
    addSystemMessage('已连接到聊天室');
};

// 接收消息
ws.onmessage = (event) => {

    try{
        const message = JSON.parse(event.data);
        addMessage(message.username, message.text, message.timestamp);
    }catch(e){
        addSystemMessage(event.data);
    }

};

// 错误处理
ws.onerror = (error) => {
    console.error('WebSocket错误:', error);
    addSystemMessage('连接发生错误');
};

// 发送消息
messageInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && messageInput.value.trim()) {
        const message = {
            username: `${userName}`,
            text: messageInput.value,
            timestamp: new Date().toISOString()
        };
        ws.send(JSON.stringify(message));
        messageInput.value = '';
    }
});

// 添加消息到界面
function addMessage(username, text, timestamp) {
    const messageElement = document.createElement('div');
    messageElement.className = 'message';
    messageElement.innerHTML = `
                <div class="avatar">${username.charAt(0).toUpperCase()}</div>
                <div class="message-content">
                    <div class="username">${username}</div>
<!--                    <div class="timestamp">${timestamp}</div>-->
                    <div>${text}</div>
                </div>
            `;
    messagesContainer.appendChild(messageElement);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

// 添加系统消息
function addSystemMessage(text) {
    const messageElement = document.createElement('div');
    messageElement.className = 'message system';
    messageElement.innerHTML = `
                <div style="width: 100%; text-align: center; color: #72767d; margin: 16px 0;">
                    ${text}
                </div>
            `;
    messagesContainer.appendChild(messageElement);
}